package cn.xiaobai.service.impl;

import cn.xiaobai.service.IClipboardService;
import cn.xioabai.common.utility.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Objects;

/**
 * @Author yangdaji
 * @Date 2022/10/11 0011
 * @PackageName com.supconit.suptap.gateway.xiaobai.service.impl
 * @ClassName ClipboardServiceImpl
 */
@Slf4j
@Service
public class IClipboardServiceImpl implements IClipboardService {

    private String oldText = null;
    private String newText = null;

    @Override
    public void save2Txt(String filePath) {
        // 未指定文件位置, 默认存入 C 盘
        if (StringUtils.isEmpty(filePath)) {
            String path;
            filePath = "C:/clipboard";
            File file = new File(filePath);
            //文件不存在进行创建
            if (!file.exists()) {
                file.mkdirs();
            }
            path = filePath + "/context.txt";
            writeFile(path);
        } else {
            String parentDirectory = slashHandel(filePath);
            File file = new File(parentDirectory);
            if (!file.exists()) {
                file.mkdirs();
            }
            writeFile(filePath);
        }
    }

    @Override
    public String getClipboardText() {
        Transferable contents = getTransferableObj();
        try {
            if (Objects.nonNull(contents) &&
                    contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                // 返回粘贴板内容
                newText = (String) contents.getTransferData(DataFlavor.stringFlavor);
                if (Objects.equals(oldText, newText)) {
                    return "";
                } else {
                    // 覆盖旧值
                    oldText = newText;
                    return newText;
                }
            }
        } catch (UnsupportedFlavorException e) {
            log.error("类型不匹配: {}", e.getMessage());
        } catch (IOException e) {
            log.error("获取内容失败: {}", e.getMessage());
        }
        return "";
    }

    @Override
    public void setClipboardText(String text) {
        Transferable selection = new StringSelection(text);
        // 设置字符串内容到粘贴板中
        Clipboard systemClipboard = getSystemClipboard();
        try {
            systemClipboard.setContents(selection, null);
        } catch (IllegalStateException e) {
            log.error("当前粘贴板不可用: {}", e.getMessage());
        }
    }

    /**
     * 写入到指定文件中
     *
     * @param filePath 文件位置
     */
    private void writeFile(String filePath) {
        //读取粘贴板内容进行写入到目标文本中
        // 获取粘贴板内容
        String clipboardText = getClipboardText();
        if (!StringUtils.isEmpty(clipboardText)) {
            try (OutputStreamWriter out = new OutputStreamWriter(
                    new FileOutputStream(filePath, true), "UTF-8")) {
                out.write(DateUtils.dateToString() + " " + clipboardText);
                out.write("\n");
                out.flush();
                log.info("写入成功: {}", clipboardText);
            } catch (Exception e) {
                log.error("写入失败: {}", e.getMessage());
            }
        }
    }


    /**
     * 获取系统粘贴板对象
     *
     * @return 返回粘贴板对象
     */
    private Clipboard getSystemClipboard() {
        return Toolkit.getDefaultToolkit()
                .getSystemClipboard();
    }

    /**
     * 获取数据转移对象
     *
     * @return 返回可转移对象
     */
    private Transferable getTransferableObj() {
        Clipboard systemClipboard = getSystemClipboard();
        try {
            return systemClipboard
                    .getContents(null);
        } catch (IllegalStateException e) {
            log.error("当前粘贴板不可用: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 斜杠处理
     *
     * @param path 路径
     * @return
     */
    private String slashHandel(String path) {
        if (path.contains("/")) {
            return path.substring(0, path.lastIndexOf("/"));
        } else if (path.contains("\\")) {
            return path.substring(0, path.lastIndexOf("\\"));
        }
        return null;
    }


}
